package com.erju.controller;


import com.alibaba.druid.util.StringUtils;
import com.erju.dao.UserMapper;
import com.erju.pojo.User;
import com.erju.service.UserService;
import com.erju.utils.RedisUtil;
import com.erju.utils.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Description: 用户管理
 * @author: 86132
 * @date: 2022.03.08
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    @Autowired
    UserService userService;

    @Autowired
    UserMapper userMapper;
    @Autowired
    RedisUtil redisUtil;

    /**
     * 插入用户
     */
    @RequestMapping("/addUser")
    public Result<?> addUser(@RequestBody User user) {
        log.info("准备插入用户-----" + user.toString());
        Result<?> result = userService.insertUser(user);
        return result;
    }

    /**
     * 查询所有用户
     *
     * @return
     */
    @RequestMapping("/selectAllUser")
    public Result<?> selectAllUser() {
        log.info("准备查询所有的用户----");
        Result<?> result = userService.findAllUser();
        return result;
    }

    /**
     * 查询用户
     *
     * @return
     */
    @RequestMapping("/selectUser")
    public Result<?> selectUser(@RequestBody User user) {
        log.info("准备查询指定的用户----");
        Result<?> result = userService.findUser(user);
        return result;
    }

    /**
     * id查询用户
     *
     * @return
     */
    @RequestMapping("/selectById")
    public Result<?> selectById(@RequestBody HashMap map) {
        int id = (Integer) map.get("id");

        log.info("准备查询指定的用户----" + id);
        Result<?> result = userService.selectById(id);
        return result;
    }

    /**
     * 更新用户信息
     *
     * @return
     */
    @RequestMapping("/updateUser")
    public Result<?> updateUser(@RequestBody User user) {
        log.info("准备更新指定的用户----" + user.toString());
        Result<?> result = userService.updateUser(user);
        return result;
    }

    /**
     * 更新用户信息
     *
     * @return
     */
    @RequestMapping("/deleteUser")
    public Result<?> deleteUser(@RequestBody User user) {
        log.info("准备删除指定的用户----" + user.toString());
        Result<?> result = userService.deleteUser(user);
        return result;
    }

    /**
     * 根据用户名查权限
     *
     * @param account
     * @return
     */
    @RequestMapping("/selectPermissions")
    public Result<?> selectPermissionsByUserName(String account) {
        User user = userService.selectPermissionsByUserName(account);
        String[] permissions = user.getPermissions().split(",");
        HashMap<String, Object> map = new HashMap<>();
        map.put("permissions", permissions);
        return Result.success("查询成功", map);
    }

    /**
     * EXCEL批量写入数据
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        return userService.upLoad(file);
    }

    /**
     * 上传头像
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/uploadPicture")
    public Result uploadpicture(MultipartFile file, @RequestParam String username) throws IOException {
        System.out.println("usermame要更新头像-->" + username);
        String baseUrl = "http://";
        String url = userService.uploadPicture(file, username);
        if (!baseUrl.equals(url)) {
            return Result.success("上传成功", url);
        } else {
            return Result.error("上传失败");
        }

    }


    /**
     * EXCEL导出学生信息
     *
     * @param response
     * @return
     * @throws IOException
     */
    @GetMapping("/downloadFailedUsingJson")
    public void downloadFailedUsingJson(HttpServletResponse response) throws IOException {
        userService.downloadFailedUsingJson(response);
    }

    /**
     * 分页查询
     *
     * @param map
     * @return
     */
    @RequestMapping("/selectAllPage")
    public Result selectAllPage(@RequestBody HashMap<String, String> map) {

        return userService.selectAllPage(map);
    }

    /**
     * 根据用户名（学号，工号）查询个人信息
     *
     * @param account
     * @return
     */
    @RequestMapping("/selectPersonalDetails")
    public Result selectPersonalDetails(String account) {
        return userService.selectPersonalDetails(account);
    }

    /**
     * 根据用户名（学号，工号）修改个人信息 点保存的时候调用这个方法
     * 只能修改 头像 手机号，qq号，微信号，邮箱
     * 修改之前先查到，带到前端 查的过程交给service层
     *
     * @param user
     * @return
     */
    @PostMapping("/updatePersonalDetails")
    public Result updatePersonalDetails(@RequestBody User user) {
        return userService.updatePersonalDetails(user);
    }

    /**
     * 根据用户名（学号，工号）修改登陆密码
     * map 里有 用户名，旧密码 新密码 确认新密码
     * {
     * "username" : "",
     * "oldpassword" : "",
     * "newpassword" : "",
     * "newpasswordAgain" : ""
     * "newpasswordAgain" : ""
     * }
     *
     * @param
     * @return
     */
    @PostMapping("/updatePassWod")
    public Result updatepassword(@RequestBody HashMap<String, String> map) {
        return userService.updatePassword(map);
    }

    /**
     * 获取手机号验证码
     *
     * @return
     */
    @RequestMapping("/getcaptcha/{phone_number}")
    public Result getCaptcha(@PathVariable("phone_number") String phone_number) {
        log.info("手机号查询验证码" + phone_number);
        //检测数据库是否含有该用户
        User user = userMapper.selectByPhoneNumber(phone_number);
        if(user==null){
            return Result.fail(502,"不存在该用户",null);
        }
        //生成验证码
        String code = redisUtil.get(phone_number);
        if (!StringUtils.isEmpty(code)) {
            //验证码不为空
            System.out.println(phone_number + ":" + code + "已经存在，还没有过期");
            return Result.fail(502,"验证码已经存在，还没有过期",null);
        }
        //验证码为空或者验证码已经过期 生成动态验证码
        log.info("验证码不存在，正在生成------");
        System.out.println("验证码不存在，正在生成");
        code = UUID.randomUUID().toString().substring(0, 4);
        Map<String, Object> codeMap = new HashMap<>();
        codeMap.put("code", code);
        //发送验证码
        boolean isSend = userService.getCaptcha(phone_number,"SMS_219621367", codeMap);

        if (isSend) {
            //验证码发送成功
            redisUtil.set(phone_number, code, 5);
            return Result.success("200","发送成功",null);
        } else {
            return Result.fail(502,"发送失败",null);
        }
    }

    /**
     * 手机号更改密码
     * @return
     */
    @RequestMapping("/phonenumberResetPassword")
    public Result phonenumberResetPassword(@RequestParam("phone_number")String phone_number,@RequestParam("captcha")String captcha,@RequestParam("newPassword")String newPassword) {
        return userService.phonenumberResetPassword(phone_number,captcha,newPassword);
    }
    @RequestMapping("/")
    public String toLogin() {
        return "index";
    }


}
